//Defining map as a global variable to access from other functions
var map;
var infowindow = null;

function initMap() {
  //Enabling new cartography and themes
  google.maps.visualRefresh = true;

  //Setting starting options of map
  var mapOptions = {
    center: new google.maps.LatLng(-16.503952, -68.129520),
    zoom: 10,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  //Getting map DOM element
  var mapElement = document.getElementById('mapDiv');

  //Creating a map with DOM element which is just obtained
  map = new google.maps.Map(mapElement, mapOptions);

  google.maps.event.addListener(map, 'click', function(e) {
    if (infowindow != null)
      infowindow.close();

    infowindow = new google.maps.InfoWindow({
      content: '<b>Parada ' + $( '[name="nombre"]' )[0].value + ' : </b><br><b>Latitude : </b>' + e.latLng.lat() + '<br><b>Longitude: </b>' + e.latLng.lng(),
      position: e.latLng
    });
    infowindow.open(map);

    $( '[name="latitud"]' )[0].value = e.latLng.lat();
    $( '[name="longitud"]' )[0].value = e.latLng.lng();
  });
}

google.maps.event.addDomListener(window, 'load', initMap);
